package com.group.controller;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.cloudauth.model.v20180504.GetStatusRequest;
import com.aliyuncs.cloudauth.model.v20180504.GetStatusResponse;
import com.aliyuncs.cloudauth.model.v20180504.GetStatusResponse.Data;
import com.base.view.BaseResult;
import com.base.view.GeneralResult;
import com.group.model.*;
import com.group.util.NoteException;
import com.group.util.WeiXinUtils;

/**
 * 用户
 * 
 * @author zhaolei
 *
 */
@Controller
public class UserController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	/**
	 * 查询当前登录用户
	 * 
	 * @param request
	 * @return @throws Exception @throws
	 */
	@GetMapping("/weixin/whoami")
	@ResponseBody
	public GeneralResult<User> whoami(HttpServletRequest request) throws Exception {
		User user = getUser(request);
		if(user!=null){
            // 补充用户wecc钱包
            tickerService.getUserTicker(user.getId(), "wecc");
        }
        return new GeneralResult<User>().setValue(user);
	}

	/**
	 * url跳转,去微信取openid
	 * 
	 * @param id
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/weixin/auth/openid")
	public RedirectView urlRedirect(Long id, Long qrid, String redirectUrl, String qyopenid, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		if (id == null) {
			UrlMapping exist = beanDao.quickQueryOne(UrlMapping.class, "url", redirectUrl);
			if (exist != null) {
				id = exist.getId();
			} else {
				UrlMapping um = new UrlMapping();
				um.setUrl(redirectUrl);
				beanDao.save(um);
				id = um.getId();
			}
		}
        User user = getUser(request);
		if(user!=null){
			if (StringUtils.isNotEmpty(user.getUnionid())) {
				String url = beanDao.quickQueryOne(UrlMapping.class, "id", id).getUrl();
				logger.info("用户user id = " + user.getId() + "已经缓存，直接跳转 : " + url);
				return new RedirectView(url);
			}
		}
		// 微信授权
		String wxurl = WeiXinUtils.createInfoUrl(id + "__" + qrid + "__" + qyopenid, getSystemParaValue("baseUrl") + "/v1/weixin/auth/redirect");
		logger.info(" 微信授权openid跳转到 url = " + wxurl);
		return new RedirectView(wxurl);
	}

	/**
	 * 获取openid
	 * 
	 * @param request
	 * @param state
	 * @param code
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/weixin/auth/redirect", method = RequestMethod.GET)
	@ResponseBody
	public RedirectView redirect(HttpServletRequest request, String state, String code, HttpServletResponse response) throws Exception {
		// 获取openid
		logger.info("微信接口回调 : code = " + code + " , state = " + state);
		WeiXinToken token = new WeiXinToken(code);
		String openid = token.getOpenid();
		WeiXinUser wxuser = new WeiXinUser(token.getAccess_token(), openid);

		Long umId = Long.parseLong(state.split("__")[0]);
		UrlMapping um = beanDao.quickQueryOne(UrlMapping.class, "id", umId);
		if (um == null) {
			throw new NoteException("error");
		}

		String qyOpenid = state.split("__")[2];
		User user = beanDao.quickQueryOne(User.class, "openid", openid);
		// 注册用户
		if (user == null) {
			user = getUser(request);
			if(user != null){
				user.setOpenid(openid);
				beanDao.save(user);
			}else{
				logger.info("注册新用户");
				user = new User();
				user.setOpenid(openid);
				// 头像转存到本地
				user.setHeadimage(weiXinUtils.getNetImage(wxuser.getHeadimgurl()));
				user.setSex(wxuser.getSex());
				user.setUuid(UUID.randomUUID().toString());
				user.setName(wxuser.getNickname());
				user.setType("普通用户");
				user.setProvince(wxuser.getProvince());
				user.setCity(wxuser.getCity());
				user.setCountry(wxuser.getCountry());
				user.setUnionid(wxuser.getUnionid());
				logger.info("注册新用户的Unionid"+wxuser.getUnionid());
				if (!"null".equals(qyOpenid))
					user.setQyOpenid(qyOpenid);
				beanDao.save(user);
				// 默认关注板块
				BoardLike bd1 = new BoardLike();
				bd1.setBoardId(2l);
				bd1.setUserId(user.getId());
				beanDao.save(bd1);

				bd1.setId(null);
				bd1.setBoardId(5l);
				bd1.setUserId(user.getId());
				beanDao.save(bd1);

				bd1.setId(null);
				bd1.setBoardId(58l);
				bd1.setUserId(user.getId());
				beanDao.save(bd1);

				bd1.setId(null);
				bd1.setBoardId(81l);
				bd1.setUserId(user.getId());
				beanDao.save(bd1);
			}
		} else {
			// 如果是微信头像,更新之
			if (user.getHeadimage() != null && user.getHeadimage().startsWith("http")) {
				// user.setHeadimage(wxuser.getHeadimgurl());
				// beanDao.save(user);
			}
			if (user.getOpenid() == null) {
				// 补充app用户的openid
				user.setOpenid(openid);
				beanDao.save(user);
			}
			if (user.getUnionid() == null) {
				user.setUnionid(wxuser.getUnionid());
				beanDao.save(user);
			}
			if (!"null".equals(qyOpenid) && (user.getQyOpenid() == null || "null".equals(user.getQyOpenid()))) {
				user.setQyOpenid(qyOpenid);
				beanDao.save(user);
			}
		}

		String qridStr = state.split("__")[1];
		if (!"null".equals(qridStr)) {
			Long qrid = Long.parseLong(qridStr);
			Qrcode qrcode = new Qrcode();
			qrcode.setId(qrid);
			qrcode.setUserId(user.getId());
			beanDao.save(qrcode);
		}

		// 加入cookie
		addUserToCookie(response, user.getUuid());
		addUserCookie(response, "openid", openid);
		logger.info("openid = " + openid);

		// 添加登录日志
		UserLoginLog log = new UserLoginLog();
		log.setUserId(user.getId());
		log.setName(user.getName());
		log.setDate(df.format(new Date()));
		beanDao.save(log);
		return new RedirectView(um.getUrl());
	}

	/**
	 * 登出接口
	 *
	 * @param response
	 * @return
	 */
	@GetMapping("/user/logout")
	@ResponseBody
	public BaseResult logout(HttpServletResponse response) {
		addUserToCookie(response, "");

		return new BaseResult();
	}

	/**
	 * 登录
	 *
	 * @param tel
	 * @param code
	 * @return
	 */

	@GetMapping("/user/login")
	@ResponseBody
	public GeneralResult<User> login(String tel, Integer code, HttpServletRequest request, HttpServletResponse response) {
		if (code == null) {
			throw new NoteException("code 不能为空");
		}
		// 判断验证码是否合法
		if (code != null) {
			if (beanDao.queryOne(new VerifyCode(tel, code)) == null)
				throw new NoteException("验证码错误");
		}

		String openid = null;

		try {
			openid = getUserOpenid(request);
		} catch (Exception e) {
		}

		User user = null;
		logger.info("用户的openid请一定记住"+openid);
		if (tel != null) {
			user = beanDao.quickQueryOne(User.class, "tel", tel);
		}else{
			if (openid != null) {
				user = beanDao.quickQueryOne(User.class, "openid", openid);
				if(user !=null){
					if (StringUtils.isEmpty(user.getTel())) {
						user.setTel(tel);
						beanDao.save(user);
					}
				}
			}
		}

		if (user == null) {
			user = new User();
			user.setTel(tel);
			user.setUuid(UUID.randomUUID().toString());
			beanDao.save(user);
			//新用户保存到ActUser
			ActUser au = new ActUser();
			au.setUserId(user.getId());
			au.setCreateTime(new Date());
			beanDao.save(au);

		}

		addUserToCookie(response, user.getUuid());

		return new GeneralResult<User>().setValue(user);
	}

	/**
	 * 测试获取openid
	 */
	@RequestMapping("/weixin/userinfo")
	@ResponseBody
	public GeneralResult<String> getUserOpenid1(HttpServletRequest request) {
		String openid = getUserOpenid(request);

		return new GeneralResult<String>().setValue(openid);
	}

	/**
	 * 获取token
	 *
	 * @return
	 */
	@RequestMapping("/weixin/token")
	@ResponseBody
	public GeneralResult<String> getToken() {

		return new GeneralResult<String>().setValue(weiXinUtils.getToken());
	}

	/**
	 * 获取JsTicket
	 *
	 * @param url
	 * @return
	 * @throws Exception
	 */
	@GetMapping("/weixin/jsticket")
	@ResponseBody
	public GeneralResult<JsTicket> GetJsTicket(String url) throws Exception {

		return new GeneralResult<JsTicket>().setValue(weiXinUtils.getJsTicket(url));
	}

	/**
	 * 修改手机号
	 *
	 * @param userId
	 * @param tel
	 * @param code
	 *            验证码
	 * @return
	 */
	@GetMapping("/user/tel")
	@ResponseBody
	public BaseResult updateTel(Long userId, String tel, Integer code) {
		if (code == null) {
			throw new NoteException("code 不能为空");
		}
		// 判断验证码是否合法
		if (code != null && code != 147258) {
			if (beanDao.queryOne(new VerifyCode(tel, code)) == null)
				throw new NoteException("验证码错误");
		}

		// 判断手机号是否已经存在
		User exist = beanDao.quickQueryOne(User.class, "tel", tel);
		if (exist != null && exist.getId() != userId.longValue()) {
			throw new NoteException("当前手机号已经存在");
		}

		User user = new User();
		user.setId(userId);
		user.setTel(tel);
		beanDao.save(user);

		return new BaseResult();
	}

	/**
	 * 修改微信
	 *
	 * @param userId
	 * @param wx
	 * @return
	 */
	@GetMapping("/user/wx")
	@ResponseBody
	public BaseResult updateWx(Long userId, String wx) {

		User user = new User();
		user.setId(userId);
		user.setWx(wx);
		beanDao.save(user);

		return new BaseResult();
	}

	/**
	 * app 添加微信用户
	 *
	 * @return
	 */
	@PostMapping(value = "/weixin/app/add")
	@ResponseBody
	public GeneralResult<User> addAppUser(@RequestBody WeiXinUser wxuser, HttpServletResponse response) {
		logger.info("app 登录用户 : " + JSONObject.toJSONString(wxuser));
		if (StringUtils.isEmpty(wxuser.getUnionid())) {
			throw new NoteException("unionid 不能为空");
		}

		User exist = beanDao.quickQueryOne(User.class, "unionid", wxuser.getUnionid());
		if (exist != null) {
			if (exist.getAppOpenid() == null) {
				exist.setAppOpenid(wxuser.getOpenid());
				beanDao.save(exist);
			}
			addUserToCookie(response, exist.getUuid());
			return new GeneralResult<User>().setValue(exist);
		}

		User user = new User();
		user.setAppOpenid(wxuser.getOpenid());
		// 头像转存到本地
		user.setHeadimage(weiXinUtils.getNetImage(wxuser.getHeadimgurl()));
		user.setSex(wxuser.getSex());
		user.setUuid(UUID.randomUUID().toString());
		user.setName(wxuser.getNickname());
		user.setType("普通用户");
		user.setProvince(wxuser.getProvince());
		user.setCity(wxuser.getCity());
		user.setCountry(wxuser.getCountry());
		user.setUnionid(wxuser.getUnionid());
		beanDao.save(user);

		addUserToCookie(response, user.getUuid());

		return new GeneralResult<User>().setValue(user);
	}

	/**
	 * 获取二维码
	 *
	 * @return
	 */
	@GetMapping("/weixin/auth/qrcode")
	@ResponseBody
	public GeneralResult<String> getQrcode() {
		Qrcode code = new Qrcode();
		code.setCreateTime(new Date());
		beanDao.save(code);

		return new GeneralResult<String>().setValue(getSystemParaValue("baseUrl") + "/v1/weixin/auth/openid?id=1&qrid=" + code.getId());
	}

	/**
	 * 根据二维码id查询用户,如果用户存在 则登录
	 *
	 * @param qrid
	 * @return
	 */
	@GetMapping("/weixin/auth/qrcode/user")
	@ResponseBody
	public GeneralResult<User> queryQrUser(Long qrid, HttpServletResponse response) {
		Qrcode code = beanDao.quickQueryOne(Qrcode.class, "id", qrid);

		if (code.getUserId() != null) {
			User user = beanDao.quickQueryOne(User.class, "id", code.getUserId());

			addUserToCookie(response, user.getUuid());

			return new GeneralResult<User>().setValue(user);
		}

		return new GeneralResult<User>().setValue(null);
	}

	/**
	 * 修改用户email
	 * 
	 * @param userId
	 * @param email
	 * @return
	 */
	@GetMapping("/user/email")
	@ResponseBody
	public BaseResult updateEmail(Long userId, String email) {

		User user = new User();
		user.setId(userId);
		user.setEmail(email);
		beanDao.save(user);

		return new BaseResult();
	}

	/**
	 * 获取短信验证码接口
	 * 
	 * @param tel
	 * @return
	 */
	@RequestMapping(value = "/user/getVerifyCode", method = RequestMethod.GET)
	@ResponseBody
	public BaseResult getVerifyCode(String tel) {
		if (StringUtils.isEmpty(tel))
			throw new NoteException("tel 不能为空");
		weiXinUtils.sendVerifyCode(tel);
		return new BaseResult();
	}

	/**
	 * 更新用户 昵称,头像,性别,关注行业,签名,背景图片等
	 * @param para
	 * @return
	 */
	@PutMapping("/user/update")
	@ResponseBody
	public GeneralResult<User> updateUser(@RequestBody User para) {
		User user = new User();
		user.setId(para.getId());
		user.setName(para.getName());
		user.setHeadimage(para.getHeadimage());
		user.setSex(para.getSex());
		user.setIndustry(para.getIndustry());
		user.setSign(para.getSign());
		user.setBackgroundImage(para.getBackgroundImage());
		beanDao.save(user);
		return new GeneralResult<User>().setValue(user);
	}

	/*public GeneralResult saveAddress(){

		return new GeneralResult<UserAddress>().setValue(userAddress);
	}*/
}
